package com.frinder.official.akka.actors;

import akka.actor.AbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import scala.concurrent.duration.Duration;
import akka.actor.AbstractActorWithTimers;

import java.util.concurrent.TimeUnit;

/**
 * Created by frinder on 2017/9/13.
 * <p>
 * 注：2.5.4 新增功能，定时任务
 */
@Component
@Scope("prototype")
public class ScheduledActor extends AbstractActorWithTimers {

    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

    private static Object TICK_KEY = "TickKey";

    private static final class FirstTick {
    }

    private static final class Tick {
    }

    public ScheduledActor() {
        getTimers().startSingleTimer(
                TICK_KEY,
                new FirstTick(),
                Duration.create(500, TimeUnit.MILLISECONDS)
        );
    }

    @Override
    public AbstractActor.Receive createReceive() {
        return receiveBuilder()
                .match(FirstTick.class, message -> {
                    log.debug("Received FirstTick message: {}", message);
                    // do something useful here
                    getTimers().startPeriodicTimer(
                            TICK_KEY,
                            new Tick(),
                            Duration.create(1, TimeUnit.SECONDS)
                    );
                })
                .match(Tick.class, message -> {
                    // do something useful here
                    log.debug("Received Tick message: {}", message);
                })
                .build();
    }
}